import axios, {
    AxiosError,
    AxiosInstance,
    AxiosRequestConfig,
    AxiosRequestHeaders,
    InternalAxiosRequestConfig
} from "axios";
import configs from "@/config";
import useUserStore from "@/base/stores/modules/user";
import {ElMessage} from "element-plus";
import router from "@/base/router";
import feedback from "@/utils/feedback";
import cache from "@/utils/cache";
import {ECacheKey} from "@/config/enums";


/**
 * 创建 axios 实例
 */
const service: AxiosInstance = axios.create({
    baseURL: configs.baseUrl,
    headers: {
        'content-type': 'application/json',
        version: configs.version
    },
    timeout: 10 * 1000 // Timeout
} as AxiosRequestConfig)


/**
 * 配置请求拦截器
 */
service.interceptors.request.use(
    (config: InternalAxiosRequestConfig<any>) => {
        const token = useUserStore().token

        // 增加token 配置
        if (token) {
            (config.headers as AxiosRequestHeaders).token = token
        }
        return config
    },

    (error) => {
        return error
    }
)


/**
 * 配置响应拦截
 */
service.interceptors.response.use(
    (response) => {
        // 跳过文件下载接口的处理
        if (response.config.responseType === 'blob') {
            return response;
        }
        switch (response.data.code) {
            case 200:
                return eventResponse.success(response.data)
            case 500:
                return eventResponse.error(response.data)
            case -1:
                return eventResponse.redirect()
            case 2:
                return eventResponse.page(response.data)
            default:
                feedback.notifyError(response.data.msg)
                return eventResponse.error(response.data)

        }
    },

    (error: AxiosError<any>) => {
        if (error.config?.responseType === 'blob') {
            return Promise.reject(error);
        }
        ElMessage({type: 'error', message: error.message})
        return Promise.reject(error)
    }
)


/**
 * 事件集
 */
const eventResponse = {
    // 成功
    success: (data: CumResponse<any>) => {
        return data.data
    },

    // 失败
    error: ({code, msg}: CumResponse<any>) => {
        return Promise.reject(msg)
    },

    // 重定向
    redirect: () => {
        const userStore = useUserStore()
        userStore.logout().then(() => {
            router.push('/login').then(r => {
            })
            userStore.resetLoginInfo().then(r => r)
        })
        return Promise.reject()
    },


    // 打开新的页面
    page: ({data}: CumResponse<any>) => {
        window.location.href = data.url
        return data
    }
}


export default service